// loghandler.h
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QMutex>
#include <QMessageLogContext>
#include <QStandardPaths>
#include <QDebug>
#include <QCoreApplication>

class FileLogger {
public:
    static FileLogger& instance() {
        static FileLogger logger;
        return logger;
    }

    void init(const QString& logPath = "") {
        QMutexLocker locker(&mutex_);
        if (!logPath.isEmpty()) {
            logFile_.setFileName(logPath);
        } else {
            // 默认路径：用户文档目录下的 logs 文件夹

            logFile_.setFileName(QCoreApplication::applicationDirPath() + "/app.log");
                    //logFile_.setFileName(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/app.log");
        }
        if (!logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
            qCritical() << "Failed to open log file!";
            return;
        }
        logStream_ = new QTextStream(&logFile_);
    }

    ~FileLogger() {
        if (logFile_.isOpen()) {
            logFile_.close();
            delete logStream_;
        }
    }

    void log(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
        QMutexLocker locker(&mutex_);
        QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
        QString level;
        switch (type) {
            case QtDebugMsg:    level = "DEBUG"; break;
            case QtInfoMsg:     level = "INFO";  break;
            case QtWarningMsg:  level = "WARN";  break;
            case QtCriticalMsg: level = "ERROR"; break;
            case QtFatalMsg:    level = "FATAL"; break;
        }
        QString logEntry = QString("[%1] %2: %3\n")
                                .arg(timestamp)
                                .arg(level)
                                .arg(msg);
        *logStream_ << logEntry;
        logStream_->flush();
    }

private:
    FileLogger() : logStream_(nullptr) {}

    FileLogger(const FileLogger&) = delete;
    FileLogger& operator=(const FileLogger&) = delete;

    QFile logFile_;
    QTextStream* logStream_;
    QMutex mutex_;
};
